<?php
namespace Common\Controller;
use Think\Controller;

class BaseController extends Controller{
	private $Ip,$cl,$db;
    public function __construct(){
		$this->cl = curl_init();
		$this->db = M('ip');
        parent::__construct();
		
		$this->writeLog();
		
		//允许访问的方法
        $run = array('allcontent','content','addcomment');
		//判断控制器
        if(CONTROLLER_NAME == 'Article'){
            if(!in_array(ACTION_NAME,$run)&&session('username')!='dmf'){
                $this->error('权限不足');
            }
        }
		//判断控制器
        if(CONTROLLER_NAME == 'Index' && MODULE_NAME == 'Admin'){
            if(session('username')!= 'dmf'){
                $this->error('权限不足');
            }
        }
		// 网站维修重定向
#		 if($this->getClientIp()!='183.29.152.243'){
#			 header('Location: http://www.dmf95.cn/mstp_127_404/index.html');
#		 }
	}
	public function __destrust(){
		curl_close($this->cl);
	}
	//获取客户端的ip
	public function getClientIp(){
		return get_client_ip();
	}
	public function getClientLocation($ip){
		$json = S($ip);
		//无ip信息
		if(empty($json)){
			
			// 设置URL和相应的选项  
			curl_setopt($this->cl,CURLOPT_URL,"http://ip.taobao.com/service/getIpInfo.php?ip=".$ip);  
			curl_setopt($this->cl,CURLOPT_HEADER,0);  
			curl_setopt($this->cl,CURLOPT_RETURNTRANSFER,true);//将数据以字符串形式返回，而不是显示出来  
			
			$json = curl_exec($this->cl);
			S($ip,$json,86400);
		}
		return $json;
	}
	public function writeLog(){
		
		$data['ip'] = $this->getClientIp();
		$ipMsg = json_decode($this->getClientLocation($data['ip']));
		
		$data['country'] = $ipMsg->data->country;
		$data["country_id"] = $ipMsg->data->country_id;
		$data["area"] = $ipMsg->data->area;
		$data["area_id"] = $ipMsg->data->area_id;
		$data["region"] = $ipMsg->data->region;
		$data["region_id"] = $ipMsg->data->region_id;
		$data["city"] = $ipMsg->data->city;
		$data["city_id"] = $ipMsg->data->city_id;
		$data["county"] = $ipMsg->data->county;
		$data["county_id"] = $ipMsg->data->county_id;
		$data["isp"] = $ipMsg->data->isp;
		$data["isp_id"] = $ipMsg->data->isp_id;
		$data["ip"] = $ipMsg->data->ip;
		
		// print_r(json_decode($ipMsg));
		// echo '<br/>';
		// print_r($ipMsg);
		// echo '<br/>';
		// print_r($data);
		// echo '<br/>';
		// die;
		
		$flag = $this->db->data($data)->add();
		
		#var_dump($data);
		#var_dump($flag);
		#if($flag){
		#	var_dump(cg);
		#}else{
		#	print_r($db->getDbError());  
		#	var_dump(sb);
		#}
		#die;
	}
	//设置session成功返回true否则false
	public function setSession($name,$value){
		//判断是否存在当前session名
		if(!isset($_SESSION[$name])){
			//一天的时间过期
			session(array('name'=>$name,'expire'=>86400));
			session($name,$value);
			return true;
		}
		return false;
	}
}
